package cn.wolfcode.rbac.controller;

import cn.wolfcode.rbac.domain.Department;
import cn.wolfcode.rbac.domain.Employee;
import cn.wolfcode.rbac.domain.Role;
import cn.wolfcode.rbac.query.EmployeeQueryObject;
import cn.wolfcode.rbac.query.PageResult;
import cn.wolfcode.rbac.query.QueryObject;
import cn.wolfcode.rbac.service.IDepartmentService;
import cn.wolfcode.rbac.service.IEmployeeService;
import cn.wolfcode.rbac.service.IRoleService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;

import java.util.List;

@Controller
@RequestMapping("/employee")
public class EmployeeController {

    @Autowired
    private IEmployeeService employeeService;
    @Autowired
    private IDepartmentService departmentService;
    @Autowired
    private IRoleService roleService;

    @RequestMapping("/list")
    public String listAll(Model model, @ModelAttribute("qo") EmployeeQueryObject qo){
        PageResult pageResult = employeeService.query(qo);
        model.addAttribute("pageResult",pageResult);
        List<Department> departments = departmentService.listAll();
        model.addAttribute("departments",departments);
        //把载具里面的数据传递给用户看
        //请求转发
        //return "forward:/WEB-INF/views/employee/list.jsp";
        return "employee/list";
    }

    @RequestMapping("/delete")
    public String delete(Long id){
        employeeService.delete(id);
        //重定向,重新定位到一个新的请求路径
        return "redirect:/employee/list";
    }


    //跳转到input页面
    @RequestMapping("/input")
    public String input(Model model,Long id){
        //数据回显
        if (id != null) {
            Employee one = employeeService.getOne(id);
            model.addAttribute("employee",one);
        }
        //查询部门下拉框信息
        List<Department> departments = departmentService.listAll();
        model.addAttribute("departments",departments);

        //显示所有的角色信息
        List<Role> roles = roleService.listAll();
        model.addAttribute("roles",roles);

        //请求转发
        return "employee/input";
    }


    //跳转到input页面之后,填完/修改完数据信息之后,点击保存按钮
    //把数据保存到数据库,然后重定向到 employee/list 请求路径,相当于又帮我们查了一次
    @RequestMapping("/saveOrUpdate")
    public String saveOrUpdate(Employee employee,Long[] roleIds){
        employeeService.saveOrUpdate(employee,roleIds);
        //保存/修改之后, 重定向到employee/list请求路径,相当于重新查询了一次最新的数据
        return "redirect:/employee/list";
    }
}
